﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bloodbank.Dto;

namespace Bloodbank.Api
{
    public class CheckedLoginApi
    {
        private BloodbankDbEntities contextDB = new BloodbankDbEntities();

        public CheckedLoginApi() {
            contextDB = new BloodbankDbEntities();
        }

        public CheckLoginDto CheckedLogin(string username, string password)
        {
            CheckLoginDto checkedLogin = new CheckLoginDto();
            try
            {
                var objUser = contextDB.Users.First(attr => attr.Username == username && attr.Password == password);
                checkedLogin.IsSuccess = true;
                checkedLogin.Permission = 0;
                checkedLogin.UserId = objUser.Id;
                checkedLogin.Username = objUser.Username;
                checkedLogin.Message = "Login is successful";
                return checkedLogin;
            }
            catch (Exception ex)
            {
                try
                {
                    var objAdmin = contextDB.Admins.First(attr => attr.Username == username && attr.Password == password);
                    checkedLogin.IsSuccess = true;
                    checkedLogin.Permission = 1;
                    checkedLogin.UserId = objAdmin.Id;
                    checkedLogin.Username = objAdmin.Username;
                    checkedLogin.Message = "Login is successful";
                    return checkedLogin;
                }
                catch (Exception exx)
                {
                    checkedLogin.IsSuccess = false;
                    checkedLogin.Message = "Username or Password is incorrect";
                    return checkedLogin;
                }
            }
        }

        public CheckLoginDto CheckExistsUser(string username)
        {
            CheckLoginDto checkedLogin = new CheckLoginDto();
            try
            {
                User objUser = contextDB.Users.First(attr => attr.Username == username);
                checkedLogin.IsSuccess = true;
                checkedLogin.Message = "Account already exists";
                return checkedLogin;
            }
            catch (Exception ex)
            {
                try
                {
                    Admin objLogin = contextDB.Admins.First(attr => attr.Username == username);
                    checkedLogin.IsSuccess = true;
                    checkedLogin.Message = "Account already exists";
                    return checkedLogin;
                }
                catch (Exception exx)
                {
                    checkedLogin.IsSuccess = false;
                    return checkedLogin;
                }
            }
        }
    }
}
